package org.adream.account.service;

import java.util.List;

import javax.servlet.http.HttpSession;

import org.adream.account.dao.CategoryDao;
import org.adream.account.entity.CategoryEntity;
import org.adream.account.model.CategoryVo;
import org.adream.account.model.ResultModel;
import org.adream.account.util.Constant;
import org.adream.account.util.Utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

/**
 * 后台类别管理 service
 * 
 * @author chenhaoyu
 *
 */
@Service
public class CategoryService {
	
	@Autowired
	private CategoryDao categoryDao;
	
	@Autowired
	private HttpSession session;

	private final static Logger logger = LoggerFactory.getLogger(CategoryService.class);

	/**
	 * 添加 Category
	 * @param categoryEntity
	 */
	public ResultModel<String> addCategory(CategoryEntity categoryEntity) {
		String operator = (String) session.getAttribute("uid");
		categoryEntity.setCreator(operator);
		categoryEntity.setModifier(operator);
		categoryEntity.setDr(Constant.ONE);
		int result = categoryDao.addCategory(categoryEntity);
		if(result == 0) {
			logger.warn("新增类别数据失败,数据库错误,title:{}", categoryEntity.getTitle());
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误,请联系系统管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}

	/**
	 * 根据 categoryId 逻辑删除
	 * @param categoryId
	 */
	public ResultModel<String> deleteCategoryById(int categoryId) {
		CategoryEntity categoryEntity = categoryDao.queryCategoryById(categoryId);
		if(categoryEntity == null) {
			logger.warn("删除类别失败,数据不存在,categoryId:{}", categoryId);
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "删除失败,数据不存在", null);
		}
		String modifier = (String) session.getAttribute("uid");
		categoryEntity.setModifier(modifier);
		int result = categoryDao.deleteCategoryById(categoryEntity);
		if(result == 0) {
			logger.warn("删除企业规模数据失败,数据库错误,categoryId:{}", categoryId);
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误,请联系系统管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}

	/**
	 * 根据 categoryPid 逻辑删除
	 * @param pid
	 * @throws ADreamServiceException 
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = ADreamServiceException.class, isolation = Isolation.DEFAULT)
	public ResultModel<String> deleteCategoryByPid(int pid) throws ADreamServiceException {
		List<CategoryEntity> categories = categoryDao.queryCategoryByPid(pid, Constant.ONE);
		if(Utils.isEmptyCollection(categories)) {
			logger.warn("删除类别失败,数据不存在,pid:{}", pid);
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "删除失败,数据不存在", null);
		}
		String modifier = (String) session.getAttribute("uid");
		int categoriesSize = categories.size();
		for (int i = 0; i < categoriesSize; i++) {
			CategoryEntity categoryEntity = categories.get(i);
			categoryEntity.setModifier(modifier);
			int result = categoryDao.deleteCategoryById(categoryEntity);
			if(result == 0) {
				throw new ADreamServiceException("根据父类别删除失败");
			}
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}

	/**
	 * 根据 categoryId 更新Category
	 * @param categoryId
	 * @param categoryEntity
	 */
	public ResultModel<String> updateCategoryById(int categoryId, CategoryEntity categoryEntity) {
		CategoryEntity category = categoryDao.queryCategoryById(categoryId);
		if(category == null) {
			logger.warn("更新类别失败,数据不存在,categoryId:{}", categoryId);
			return new ResultModel<String>(ResultModel.NOT_FOUND_OBJECT, "更新失败,数据不存在", null);
		}
		String modifier = (String) session.getAttribute("uid");
		category.setModifier(modifier);
		category.setTitle(categoryEntity.getTitle());
		category.setPid(categoryEntity.getPid());
		int result = categoryDao.updateCategoryById(category);
		if(result == 0) {
			logger.warn("更新类别失败,数据库错误,categoryId:{}", categoryId);
			return new ResultModel<String>(ResultModel.ERR_SYS, "系统错误,请联系系统管理员", null);
		}
		return new ResultModel<String>(ResultModel.SUCCESS, ResultModel.SUCCESS_MSG, null);
	}

	/**
	 * 查询所有的 category
	 * 
	 * @return
	 */
	public List<CategoryEntity> queryCategory() {
		return categoryDao.queryCategory();
	}

	/**
	 * 根据 categoryId 查询 category
	 * @param categoryId
	 * @return
	 */
	public CategoryEntity queryCategoryById(int categoryId) {
		return categoryDao.queryCategoryById(categoryId);
	}

	/**
	 * 根据 pid 查询 category
	 * 
	 * @param pid
	 * @return
	 */
	public List<CategoryEntity> queryCategoryByPid(int pid) {
		return categoryDao.queryCategoryByPid(pid, Constant.ONE);
	}

	/**
	 * 根据 逻辑状态查询category
	 * 
	 * @param dr
	 * @return
	 */
	public List<CategoryEntity> queryCategoryByDr(int dr) throws ADreamServiceException {
		return categoryDao.queryCategoryByDr(dr);
	}

	/**
	 * 检查Category 是否合法 (查重)
	 * 
	 * @param title
	 * @return true合法 false不合法
	 */
	public boolean isValidCategoryTitle(String title) {
		boolean isValid = false;
		if (!StringUtils.isEmpty(title) && categoryDao.queryCategoryTitleExistence(title) == Constant.ZERO) {
			isValid = true;
		}
		return isValid;
	}

	/**
	 * 模糊查询 如果无关键词，则查询所有逻辑存在的row
	 * 
	 * @param keyword
	 * @param pageNo 当前页数
	 * @param pageSize 当前页的数量
	 * @return
	 */
	public PageInfo<CategoryVo> queryCategoryByKeywordAndPid(String keyword,String pid, Integer pageNo, Integer pageSize) {
		pageNo = (pageNo == null) ? Constant.ONE : pageNo;
		pageSize = (pageSize == null) ? Constant.TEN : pageSize;
		PageHelper.startPage(pageNo, pageSize);
		//如果分类选择的是all，则全部查询
		if ("all".equals(pid)) {
			pid = null;
		}
		List<CategoryVo> list = categoryDao.queryCategoryByKeywordAndPid(keyword,pid,1);
		PageInfo<CategoryVo> page = new PageInfo<>(list, Constant.NINE);
		return page;
	}
}